package com.cloud.spring.environment;

import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.ApplicationListener;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class StartReadConfiguration implements EnvironmentAware, ApplicationListener<ContextRefreshedEvent> {
    private StandardEnvironment environment;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        init();
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (StandardEnvironment) environment;
    }

    // todo  有的版本不支持修改  为只读map
    public void init() {
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.forEach(propertySource -> {
            if (propertySource instanceof OriginTrackedMapPropertySource) {
                OriginTrackedMapPropertySource originTrackedMapPropertySource
                        = (OriginTrackedMapPropertySource) propertySource;
                // 新增配置mayikt.name==yushengjun
                // todo  有的版本不支持修改  为只读map
//                Map map = originTrackedMapPropertySource.getSource();
//                map.put("mayikt.name", "yushengjun");
            }
        });
    }
}